<template>
	<view class="hb-comment" >
		
		<uv-popup ref="popup" mode="bottom" round="20" @change="change">
			<view class="d-pinglun-0" :style="{height: gaodu + 'px'}">
				<view  class="d-neikuang-40" :style="{height: gaodu + 'px'}">
					<!--评论-->
					<scroll-view 
					  scroll-y
					  :style="{'height': gaodu + 'px','margin-bottom':'500rpx','overflow-y':'auto'}"
					  @scrolltolower="loadMore"
					  :lower-threshold="50"
					>
						<uv-divider :text="'评论 ' + commentData.readNumer + '条'"></uv-divider>
						
						<!-- 评论主体-start -->
						<view class="comment-list" v-if="commentData.comment.length != 0" >
							<view class="comment-box" v-for="(item, index) in commentData.comment">
					            <view class="comment-box-item">
									<view>
										<image :src="item.avatarUrl || emptyAvatar" mode="aspectFill" class="avatar"></image>
									</view>
									<view class="comment-main">
										<view class="comment-main-content" >
											<view class="beijing-10" @click="reply(item.nickName,item.nickName,item.id,item.content)">
												<view class="comment-main-top">
													<view class="nick-name-box">
														<view class="nick-name">{{item.nickName}}</view>
											        </view>
													<view class="zan-box" >
														<view class="foot-time" >{{item.createTime}}</view>
													</view>
												</view>
											    
												{{item.content.length > 60 ? item.content.slice(0, 59) : item.content}}
											</view>



											<span v-if="item.content.length > 60">
												{{item.hasShowMore ? item.content.slice(59) : '...'}}
												<span class="foot-btn" @click="showMore(item.id)">
													{{item.hasShowMore ? '收起' : '展开'}}
												</span>
											</span>
											<view v-if="item.yinyong && item.yinyong.content" class="beijing-11 d-chaochu-2 d-shang-5">
												{{ item.yinyong.author }} : {{ item.yinyong.content }}
											</view>
										</view>
										<view class="comment-main-foot" >
											<!--view class="foot-time" >{{item.createTime}}</view-->
											<!--view class="foot-btn" @click="reply(item.nickName,item.nickName,item.id)">回复.</view-->
											<view class="foot-btn" v-if="item.owner" @click="confirmDelete(item.id)">删除</view>
										</view>

									</view>

								</view>

							</view>
						</view>
						<!--添加触发更多加载 下一页-->
						<view class="d-kuan" style="height: 300rpx;"></view>
						
						<!-- 加载状态指示器 -->
						<view class="loading-indicator" v-if="isLoading">
							<text>加载中...</text>
						</view>
						
						<!-- 没有更多数据提示 -->
						<view class="no-more-data" v-if="noMoreData && !isLoading">
							<text>没有更多评论了</text>
						</view>
					</scroll-view>

					<!--/评论-->
				</view>
				<view v-if="pinglunxianshi==0" class="d-pinglun-1 d-pinglun-kuang-50" @click.stop="tiwenzhi()">
					<uv-search placeholder="请输入评论"  :showAction="false" searchIcon="more-circle" :focus="true"  v-model="tiwenneirong"></uv-search>
				</view>
				<view v-if="pinglunxianshi==1" class="d-pinglun-1 d-pinglun-kuang-100">
					<view class="d-pinglun-kuang-100-1">
					    <uv-textarea class="d-clear" border="none" ref="commentTextarea" :focus="true"  @input="pingluninput" @blur="handleTextareaBlur" v-model="tiwenneirong" placeholder="请输入内容"></uv-textarea>
					    <view v-if="erji_pinglun == 1" class="d-tijiao-4-pinglun d-chaochu-1 d-zuo d-zuo-5" >{{ nickName }} ： {{ yinyong_neirong }}</view>
					    <view v-if="pinglunxianshi==1" class="d-tijiao-pinglun d-you d-you-5"  @click.stop="tijiao_wenda">提交</view>
					</view>

				    
				</view>
				
				
			</view>
		</uv-popup>
	</view>
</template>

<script>
export default {
	props: {
		pinglun_xianshi_weibu: {
			type: Number,
			default: 0
		},
		cmData: {
			type: Object,
			default: () => {
				return null;
			}
		},
		deleteTip: {
			type: String,
			default: () => {
				return '操作不可逆，如果评论下有子评论，也将被一并删除，确认？';
			}
		},
		nodata: {
			type: Boolean,
		    default: false
		},
		pinglunxianshi_dibu: {
			type: Number,
			default: 0
		},
	},
	data() {
			return {
				gaodu: 0, // 高度
				visible: false,
				pinglun:'',
				tiwenneirong:'',
				pinglunxianshi:0,
				"commentData": null,
				"placeholder": "请输入评论",
				"commentReq": {
					"pId": null, // 评论父id
					"content": null // 评论内容
				},
				"pUser": null, // 标签-回复人
				"showTag": false, // 标签展示与否
				"focus": false, // 输入框自动聚焦
				"submit": false, // 弹出评论
				"KeyboardHeight": 0, // 键盘高度
				"isLoading": false,  // 加载状态
				"noMoreData": false,  // 是否还有更多数据
				"page": 1,  // 当前页码
				"pageSize": 10,  // 每页数量
				"blurTimeout": null, // 存储失去焦点的延迟计时器
				"loadingTextTimeout": null ,// 存储加载提示的延迟计时器
				erji_pinglun:0,//二级评论 
				nickName:'',//用户昵称
				yinyong_neirong:'',//二级评论内容
			}
		},
	watch: {
		// 监听pinglun_xianshi_weibu的值变化
		pinglun_xianshi_weibu(newValue) {
			if (newValue === 1 && this.$refs.popup) {
				this.$refs.popup.open();
			}
		},
		// 监听pinglunxianshi_dibu的值变化
		pinglunxianshi_dibu(newValue) {
			if (newValue === 1) {
				this.pinglunxianshi = 1;
			}
		},
		cmData: {
			handler: function(newVal, oldVal) {
				this.init(newVal);
			},
			immediate: true
		}
	},
	mounted() {
		this.updateHeight(); // 初始化高度
		// 仅微信小程序支持
		if (typeof uni.onKeyboardHeightChange === 'function') {
			uni.onKeyboardHeightChange(res => {
			this.KeyboardHeight = res.height;
			});
		} else {
			// 其他平台的替代方案
			this.KeyboardHeight = 300;
		}

	},
	methods: {
		// 初始化评论
		init(cmData) {
			// 确保cmData和cmData.comment有效
			if(!cmData || !Array.isArray(cmData.comment)) {
				console.log('无效的评论数据');
				this.isLoading = false;
				return;
			}
			
			if(this.page === 1) {
			    this.commentData = cmData;
			} else {
			    // 追加新数据
			    this.commentData.comment = [...this.commentData.comment, ...cmData.comment];
			}
			this.isLoading = false;
			// 只有在当前页码大于1并且返回的数据少于pageSize时，才认为没有更多数据
			// 这样可以确保首次加载时不会错误地显示"没有更多评论了"
			this.noMoreData = this.page > 1 && cmData.comment.length < this.pageSize;
			//console.log('初始化完成，isLoading:', this.isLoading, 'noMoreData:', this.noMoreData, 'page:', this.page, '返回数据量:', cmData.comment.length);
		},
		// 加载更多评论
		loadMore() {
			console.log('触发加载更多', {
	    	    isLoading: this.isLoading,
	    	    noMoreData: this.noMoreData,
	    	    page: this.page,
	    	    currentDataLength: this.commentData?.comment?.length || 0,
	    	    hasCommentData: !!this.commentData
	    	});
	    
	    // 确保commentData存在
	    if(!this.commentData || !this.commentData.comment) {
	    	//console.log('commentData不存在或格式不正确，不执行加载更多');
	    	return;
	    }
	    
	    // 防止重复加载和无数据时加载
	    if(this.nodata || this.isLoading || this.noMoreData) {
	    	//console.log('不满足加载条件，nodata:', this.nodata, 'isLoading:', this.isLoading, 'noMoreData:', this.noMoreData);
	    	return;
	    }
	    
	    this.isLoading = true;
	    this.page++;
	    
	    // 添加加载状态提示
	    if(this.loadingTextTimeout) clearTimeout(this.loadingTextTimeout);
	    
	    // 触发父组件加载更多数据
	    this.$emit('load-more', {
	    	page: this.page,
	    	pageSize: this.pageSize
	    });
	},
					// 没用的方法，但不要删
			stopPrevent() {},
			// 回复评论
			reply(pUser, reUser, pId, neirong) {
				/*this.pUser = pUser;
				this.commentReq.pId = pId;
				if (reUser) {
					this.commentReq.content = '@' + reUser + ' ';
				} else {
					this.commentReq.content = '';
				}
				this.showTag = true;
				this.commentInput();*/
				// 清除可能存在的blurTimeout计时器，确保textarea保持打开状态
				if(this.blurTimeout) {
					clearTimeout(this.blurTimeout);
					console.log('清除blur延迟计时器，确保回复时textarea保持打开状态');
				}
				// 设置回复相关状态
				this.pinglunxianshi = 1;
				this.nickName = pUser;
				this.yinyong_neirong = neirong;
				this.erji_pinglun = 1;
				this.$emit('tiwenzhi', pUser, reUser, pId,  neirong);
			},
			// 删除评论前确认
			confirmDelete(commentId) {
				var that = this;
				uni.showModal({
					title: '警告',
					content: that.deleteTip,
					confirmText: '确认删除',
					success: function(res) {
						if (res.confirm) {
							that.$emit('del', commentId);
						}
					}
				});
			},
			// 新增评论
			add() {
				if (this.commentReq.content == null || this.commentReq.content.length < 2) {
					uni.showToast({
						title: '评论内容过短',
						duration: 2000
					});
					return
				}
				this.$emit('add', this.commentReq);
			},
			// 点赞评论
			like(commentId) {
				this.$emit('like', commentId);
			},
			// 新增完成
			addComplete() {
				this.commentReq.content = null;
				this.tagClose();
				this.closeInput();
			},
			// 点赞完成-本地修改点赞结果
			likeComplete(commentId) {
				for (var i in this.commentData.comment) {
					if (this.commentData.comment[i].id == commentId) {
						this.commentData.comment[i].hasLike ? this.commentData.comment[i].likeNum-- : this.commentData
							.comment[i].likeNum++;
						this.commentData.comment[i].hasLike = !this.commentData.comment[i].hasLike;
						return
					}
					for (var j in this.commentData.comment[i].children) {
						if (this.commentData.comment[i].children[j].id == commentId) {
							this.commentData.comment[i].children[j].hasLike ? this.commentData.comment[i].children[j]
								.likeNum-- : this.commentData.comment[i].children[j].likeNum++;
							this.commentData.comment[i].children[j].hasLike = !this.commentData.comment[i].children[j]
								.hasLike;
							return
						}
					}
				}
			},
			// 删除完成-本地删除评论
			deleteComplete(commentId) {
				for (var i in this.commentData.comment) {
					for (var j in this.commentData.comment[i].children) {
						if (this.commentData.comment[i].children[j].id == commentId) {
							this.commentData.comment[i].children.splice(Number(j), 1);
							return
						}
					}
					if (this.commentData.comment[i].id == commentId) {
						this.commentData.comment.splice(Number(i), 1);
						return
					}
				}
			},
			// 展开评论
			showMore(commentId) {
				for (var i in this.commentData.comment) {
					if (this.commentData.comment[i].id == commentId) {
						this.commentData.comment[i].hasShowMore = !this.commentData.comment[i].hasShowMore;
						this.$forceUpdate();
						return
					}
					for (var j in this.commentData.comment[i].children) {
						if (this.commentData.comment[i].children[j].id == commentId) {
							this.commentData.comment[i].children[j].hasShowMore = !this.commentData.comment[i].children[j]
								.hasShowMore;
							this.$forceUpdate();
							return
						}
					}
				}
			},
			// 输入框失去焦点
			blur() {
				this.focus = false;
			},
			// 输入框聚焦
			focusOn() {
				this.$emit('focusOn');
			},
			// 标签关闭
			tagClose() {
				this.showTag = false;
				this.pUser = null;
				this.commentReq.pId = null;
			},
			// 输入评论
			commentInput() {
				// TODO 调起键盘方法
				this.submit = true;
				setTimeout(() => {
					this.focus = true;
				}, 50)
			},
			// 关闭输入评论
			closeInput() {
				this.focus = false;
				this.submit = false;
			},
		updateHeight() {
			const systemInfo = uni.getSystemInfoSync();
			// 直接使用px单位计算scroll-view高度
			// 减去底部操作栏高度，确保内容不被遮挡
			this.gaodu = systemInfo.windowHeight - 150; // 使用px单位，确保与scroll-view样式一致
		},
		change() {
			//this.visible = !this.visible
			//this.$refs.popup.close();
			this.$emit('pinglun_close_get');
		},
		tiwenzhi(){
				// 清除可能存在的blurTimeout计时器，确保textarea保持打开状态
				if(this.blurTimeout) {
					clearTimeout(this.blurTimeout);
					console.log('清除blur延迟计时器，确保打开textarea时保持状态');
				}
				this.pinglunxianshi = 1;
				// 在DOM更新后，设置焦点到文本末尾
			this.$nextTick(() => {
				this.$emit('tiwenzhi');
				this.erji_pinglun = 0;
				if (this.$refs.commentTextarea && this.$refs.commentTextarea.$el) {
					// 获取textarea元素
					const textarea = this.$refs.commentTextarea.$el.querySelector('textarea');
					if (textarea) {
						// 设置焦点
						textarea.focus();
						// 设置光标位置到文本末尾
						const length = textarea.value.length;
						textarea.setSelectionRange(length, length);
					}
				}
			});
		},
		handleTextareaBlur() {
		    // 添加日志以验证方法被调用
		    console.log('textarea失去焦点，延迟设置pinglunxianshi=0');
		    
		    // 添加一个短暂的延迟，避免点击提交按钮时立即隐藏按钮
		    // 这样用户可以先完成提交按钮的点击操作
		    this.blurTimeout = setTimeout(() => {
		        // 检查是否真的需要隐藏（如果用户点击了提交按钮，这个值可能已经被重置）
		        if(this.pinglunxianshi === 1) {
		            this.pinglunxianshi = 0;
		            // 强制刷新视图
		            this.$nextTick(() => {
						this.nickName = '';
						this.yinyong_neirong = '';
						this.erji_pinglun = 0;
						this.$emit('tiwenzhi');
		                //console.log('视图已更新，pinglunxianshi值为:', this.pinglunxianshi);
						this.$emit('pinglun_tijiao_dibu');
		            });
		        }
		    }, 300); // 300毫秒延迟，足够用户完成点击操作
		},
		//提交问答
		//tieid:帖子id,uid用户id,code密钥,rid级别,content评论内容,
		pingluninput(e){
			var duixin = this; 
		    let newStr = '<p>' + e + '</p>';
		    let pingluncontent = newStr.replace(/\n/g,"</p><p>");
			this.tiwenneirong = pingluncontent;
			//打印
			//console.log('评论内容',this.tiwenneirong);
		},
		tijiao_wenda(){
			// 清除blur事件的延迟计时器，防止在提交过程中隐藏按钮
			if(this.blurTimeout) {
				clearTimeout(this.blurTimeout);
				//console.log('清除blur延迟计时器');
			}
			
			//console.log('提交前评论内容:', this.tiwenneirong);
			
			// 实际提交评论数据
			if(this.tiwenneirong && this.tiwenneirong.trim()) {
				// 使用$nextTick确保DOM更新
				this.$nextTick(() => {
					// 切换回搜索框状态
					this.pinglunxianshi = 0;
					this.erji_pinglun = 0;
					//console.log('最终评论内容:', this.tiwenneirong);
					
					// 通知父组件评论已提交
					this.$emit('pinglun_tijiao', this.tiwenneirong);
					this.$emit('pinglun_tijiao_dibu');
					this.tiwenneirong = '';
                    //console.log('清空后评论内容:', this.tiwenneirong);
				});
			} else {
				//console.log('评论内容为空，不提交');
				this.$emit('pinglun_tijiao_dibu');
				uni.showToast({
					title: '评论内容不能为空',
					icon: 'none'
				});
			}
		}
	}
}
</script>

<style  lang="scss" scoped>
	.d-pinglun-0 {
		position: relative;
	}
	.d-pinglun-1 {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
	}
	.d-pinglun-kuang-50{
		height: 100rpx;
		line-height: 100rpx;
		margin: 0 20rpx;
		border-top: 1px solid #f0f0f0;
		background-color: #ffffff;
	}
	.d-pinglun-kuang-100{
		height: 240rpx;
		margin: 0 20rpx;

	}
	.d-pinglun-kuang-100-1{
	height: 210rpx;
	line-height: 100rpx;
	border-radius: 10rpx;
	border: 1px solid #dfdfdf;
	padding-bottom: 20rpx;
}
	
	.d-tijiao-pinglun {
		/*position:absolute;*/
		bottom: 30rpx;
		right:6rpx;
		z-index:99999;
		width: 100rpx;
		padding: 2rpx 0rpx;
		border-radius: 50rpx;
		background-color: #16b693;
		color: #ffffff;
		font-size: 14px;
		text-align: center;
		height: 40rpx;
		line-height: 40rpx;
		/* 确保按钮可点击 */
		pointer-events: auto;
		touch-action: manipulation;
	}
	
	/* 加载状态指示器样式 */
	.loading-indicator {
		padding: 20rpx 0;
		text-align: center;
		color: #999999;
		font-size: 28rpx;
	}
	
	/* 没有更多数据提示样式 */
	.no-more-data {
		padding: 20rpx 0;
		text-align: center;
		color: #999999;
		font-size: 28rpx;
	}
	     .beijing-10{
		background-color: #f7f7f7;
		padding: 10rpx 20rpx 20rpx 20rpx;
		border-radius: 20rpx;
		position: relative;
	 }
	 .beijing-11 {
		background-color: #f5f5f5;
		padding: 10rpx;
		border-radius: 10rpx;
		position: relative;
		font-size: 12px;
		color: #757575;
	 }
	 .beijing-10::before {
	    content: "";
	    position: absolute;
	    left: -20rpx;
	    top: 30rpx;
	    width: 0;
	    height: 0;
	    border-top: 10rpx solid transparent;
	    border-right: 20rpx solid #f5f5f5;
	    border-bottom: 10rpx solid transparent;
	}
	.hb-comment {
		padding: 10rpx;
		
    	/*overflow-y: auto;*/ /* 确保启用滚动 */
    	-webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
		/* 滚动条样式 */
		::-webkit-scrollbar {
		  width: 2px; /* 滚动条宽度 */
		  height: 5px; /* 滚动条高度 */
		}
	
	}
	/* 确保内容足够长可以滚动 */
	.comment-list {
  	  min-height: 101vh;
  	}
	.foot-time{
		font-size: 24rpx;
		padding-left: 10rpx;
		color: #b3b3b3;
	}

	.top-read {
		font-size: 28rpx;
		padding-left: 10rpx;
		color: #999999;
	}

	.seg_line_box {
		display: flex;
		height: 5rpx;
		justify-content: space-between;
		margin: 5rpx 0;
	}

	.seg_line {
		width: 45%;
		border-bottom: 1rpx solid #e1e1e1;
	}

	.seg_dot {
		width: 8%;
		border-bottom: 5rpx dotted #dbdbdb;
	}

	.comment-num {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
	}

	.comment-box {
		padding: 10rpx 0;
	}

	.comment-box-item {
		display: flex;
	}

	.comment-main {
		padding-left: 20rpx;
		width: 100% !important;
	}

	.comment-main-top {
		width: 100% !important;
		/*width: 600rpx;*/
		padding-top: 0rpx;
		display: flex;
		justify-content: space-between;
	}

	.sub-comment-main-top {
		width: 510rpx;
		padding-top: 6rpx;
		display: flex;
		justify-content: space-between;
	}

	.avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
	}
	.avatar-2 {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
	}

	.nick-name-box {
		display: flex;
		align-items: center;
	}

	.comLogo {
		margin-right: 16rpx;
		font-size: 18rpx;
		border-radius: 10rpx;
		padding: 5rpx 15rpx;
		color: #FFFFFF;
	}

	.com1 {
		background-color: #18c6d2;
	}

	.com2 {
		background-color: #18c6d2;
	}

	.com3 {
		background-color: #18c6d2;
	}

	.com4 {
		background-color: #18c6d2;
	}

	.nick-name {
		font-size: 28rpx;
		color: #848484;
	}

	.isLike {
		font-size: 30rpx;
		padding-right: 10rpx;
		color: #2fb88f;
	}

	.notLike {
		font-size: 28rpx;
		padding-right: 10rpx;
		color: #2fb88f;
	}

	.comment-main-content {
		padding: 0rpx 10rpx 10rpx 0;
	}

	.comment-main-foot {
		display: flex;
		font-size: 22rpx;
		color: #c4c4c4;
	}

	.replayTag {
		color: #909399;
		margin-bottom: 5px;
		border: 1px solid #c8c9cc;
		background-color: #f4f4f5;
		border-radius: 3px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 16rpx;
		padding: 5px 10px;
	}

	.replyTagClose {
		font-size: 20px;
		line-height: 12px;
		padding: 0 0 2px 5px;
	}

	.foot-btn {
		padding-left: 10rpx;
		color: #b4b4b4;
	}

	.comment-sub-box {
		/*padding: 20rpx 0;*/
	}

	.comment-sub-item {
		display: flex;
	}

	.comment-none {
		padding: 20rpx;
		width: 100%;
		text-align: center;
		color: #999999;
	}

	.comment-submit-box {
		position: fixed;
		display: flex;
		align-items: flex-end;
		z-index: 9900;
		left: 0;
		top: var(--window-top);
		bottom: 0;
		background-color: rgba($color: #000000, $alpha: 0.5);
		width: 100%;
	}

	.comment-add {
		position: fixed;
		background-color: #FFFFFF;
		width: 100%;
		padding: 5rpx;
		border: 1px solid #ddd;
		transition: .3s;
		-webkit-transition: .3s;
	}

	.btn-click {
		color: #007AFF;
		font-size: 28rpx;
		padding: 10rpx;
	}

	.cancel {
		color: #606266;
	}

	.textarea {
		height: 100px;
		padding: 16rpx;
		width: 100%;
	}

	.comment-submit {
		padding: 5rpx 20rpx 0 20rpx;
		border-bottom: 1px dashed #ddd;
		width: calc(100% - 40rpx);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.d-tijiao-4-pinglun {
	/*position:absolute;*/
	bottom: 30rpx;
	left:2rpx;
	z-index:9999;
	width: 70%;
	padding: 2rpx 8rpx;
	border-radius: 10rpx;
	background-color: #ebebeb;
	color: #a5a5a5;
	font-size: 12px;
	line-height: 40rpx;
	
	/*超出1*/
}

</style>